<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,concurrent," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="AtomicIntegerFieldUpdater是什么？变量线程安全的三要素并发编程中总结了线程安全变量必须满足的三个要素：  原子性所有的操作在一个原子语义中完成 可见性修改立即对主内存可见 有序性处理器为了更好的运算性能，会自动优化、排序我们的代码。线程安全应保证代码的顺序，拒绝此类优化  Java保证变量的线程安全在java中，最有效的保证线程安全的方式就是加锁，重量级锁synchroni">
<meta name="keywords" content="java,concurrent">
<meta property="og:type" content="article">
<meta property="og:title" content="java并发学习之AtomicIntegerFieldUpdater字段原子更新类">
<meta property="og:url" content="https://gitee.com/shuhao/2018/06/20/java并发学习之AtomicIntegerFieldUpdater字段原子更新类/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="AtomicIntegerFieldUpdater是什么？变量线程安全的三要素并发编程中总结了线程安全变量必须满足的三个要素：  原子性所有的操作在一个原子语义中完成 可见性修改立即对主内存可见 有序性处理器为了更好的运算性能，会自动优化、排序我们的代码。线程安全应保证代码的顺序，拒绝此类优化  Java保证变量的线程安全在java中，最有效的保证线程安全的方式就是加锁，重量级锁synchroni">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-06-23T03:25:01.761Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java并发学习之AtomicIntegerFieldUpdater字段原子更新类">
<meta name="twitter:description" content="AtomicIntegerFieldUpdater是什么？变量线程安全的三要素并发编程中总结了线程安全变量必须满足的三个要素：  原子性所有的操作在一个原子语义中完成 可见性修改立即对主内存可见 有序性处理器为了更好的运算性能，会自动优化、排序我们的代码。线程安全应保证代码的顺序，拒绝此类优化  Java保证变量的线程安全在java中，最有效的保证线程安全的方式就是加锁，重量级锁synchroni">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/06/20/java并发学习之AtomicIntegerFieldUpdater字段原子更新类/"/>





  <title> java并发学习之AtomicIntegerFieldUpdater字段原子更新类 | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/06/20/java并发学习之AtomicIntegerFieldUpdater字段原子更新类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                java并发学习之AtomicIntegerFieldUpdater字段原子更新类
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-20T08:09:23+08:00">
                2018-06-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="AtomicIntegerFieldUpdater是什么？"><a href="#AtomicIntegerFieldUpdater是什么？" class="headerlink" title="AtomicIntegerFieldUpdater是什么？"></a>AtomicIntegerFieldUpdater是什么？</h2><h3 id="变量线程安全的三要素"><a href="#变量线程安全的三要素" class="headerlink" title="变量线程安全的三要素"></a>变量线程安全的三要素</h3><p>并发编程中总结了线程安全变量必须满足的三个要素：</p>
<ol>
<li>原子性<br>所有的操作在一个原子语义中完成</li>
<li>可见性<br>修改立即对主内存可见</li>
<li>有序性<br>处理器为了更好的运算性能，会自动优化、排序我们的代码。线程安全应保证代码的顺序，拒绝此类优化</li>
</ol>
<h3 id="Java保证变量的线程安全"><a href="#Java保证变量的线程安全" class="headerlink" title="Java保证变量的线程安全"></a>Java保证变量的线程安全</h3><p>在java中，最有效的保证线程安全的方式就是加锁，重量级锁synchronize、轻量级锁ReenTrantLock；但是有的时候我们在效率之间取舍通常会适当的舍弃部分线程安全特性。例如使用volatile变量修饰的字段，仅实现了内存可见性，无法满足原子性。<br>并且，我们也可以定义线程安全的变量，避免将操作变量的整段代码加锁来提升效率。Java就提供了此类API。如：java.util.concurrent.atomic包下的类。<br>AtomicInteger可以用原子的方式更新int值。其实现原理采用的就是<a href="http://shuhao.gitee.io/blog/2018/01/25/CAS%E9%94%81%E6%9C%BA%E5%88%B6%EF%BC%8CAtomicInteger%E5%AE%9E%E7%8E%B0/" target="_blank" rel="external">CAS模式乐观锁</a>;有兴趣可以了解一下。</p>
<p>好了，讲了这么多，与AtomicIntegerFieldUpdater有什么关系呢？如果我们需要重构之前的历史代码，之前对变量的使用，没有考虑到线程安全的问题，现在需要实现线程安全，那么AtomicIntegerFieldUpdater是其中的一个选择。下面我们就来看下这一过程如何实现？</p>
<h4 id="AtomicIntegerFieldupdateUpdater创建"><a href="#AtomicIntegerFieldupdateUpdater创建" class="headerlink" title="AtomicIntegerFieldupdateUpdater创建"></a>AtomicIntegerFieldupdateUpdater创建</h4><p>在创建以及使用AtomicIntegerFieldUpdater的过程中还是有些限制：</p>
<ol>
<li>字段必须是<strong>volatile</strong>，在多线程之间保持可见性</li>
<li>AtomicIntgegerFieldUpdater修饰的参数<strong>必须是int类型</strong></li>
<li>不能操作父类对象中的实例变量</li>
<li>字段的描述类型（修饰符public/protected/default/private）是与调用者与操作对象字段的关系一致。也就是说调用者能够直接操作对象字段，那么就可以反射进行原子操作</li>
<li>只能修饰实例可修改变量，参数<strong>不可用 final 、static修饰</strong><br>以上就是我们通过AtomicIntegerFieldUpdater修饰类变量是必须遵守的一些规则。</li>
</ol>
<p>通过API可以看到AtomicIntegerFieldUpdater的构造函数被修饰为protected，以为这我们在调用API时不可直接new对象。JavaAPI也提供了一个创建对象的方法<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">public static &lt;U&gt; AtomicIntegerFieldUpdater&lt;U&gt; newUpdater(Class&lt;U&gt; tclass,  String fieldName)</span><br><span class="line"></span><br><span class="line">第一个参数为需要包装变量所在的对象的class对象，第二个参数很明显就是参数名</span><br></pre></td></tr></table></figure></p>
<p>好了，了解了AtomicIntegerFieldUpdater来看下其如何包装变量使得其实现原子性。</p>
<h3 id="AtomicIntegerFieldUpdater使用"><a href="#AtomicIntegerFieldUpdater使用" class="headerlink" title="AtomicIntegerFieldUpdater使用"></a>AtomicIntegerFieldUpdater使用</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.concurrent.CountDownLatch;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.atomic.AtomicIntegerFieldUpdater;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by Niki on 2018/6/22 9:21</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AtomicIntegerFieldUpdateDemo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> index_unsafe = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> index_safe = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        AtomicIntegerFieldUpdateDemo demo = <span class="keyword">new</span> AtomicIntegerFieldUpdateDemo();</span><br><span class="line">        demo.unsafeIncr();</span><br><span class="line">        demo.safeIncr();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> AtomicIntegerFieldUpdateDemo demo ;</span><br><span class="line">        CountDownLatch latch;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Test</span><span class="params">(AtomicIntegerFieldUpdateDemo demo, CountDownLatch latch)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.demo = demo;</span><br><span class="line">            <span class="keyword">this</span>.latch = latch;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Test</span><span class="params">(AtomicIntegerFieldUpdateDemo demo)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.demo = demo;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            demo.index_unsafe ++;</span><br><span class="line">            latch.countDown();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">500</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">unsafeIncr</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CountDownLatch latch = <span class="keyword">new</span> CountDownLatch(<span class="number">50000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">50000</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> Thread(<span class="keyword">new</span> Test(<span class="keyword">this</span>,latch)).start();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">           latch.await();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"非线程安全自增值："</span> + <span class="keyword">this</span>.index_unsafe);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">safeIncr</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> AtomicIntegerFieldUpdater&lt;AtomicIntegerFieldUpdateDemo&gt; safe = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdateDemo.class, <span class="string">"index_safe"</span>);</span><br><span class="line">        CountDownLatch latch = <span class="keyword">new</span> CountDownLatch(<span class="number">5000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5000</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> Thread(()-&gt;&#123;</span><br><span class="line">                safe.addAndGet(<span class="keyword">this</span>, <span class="number">1</span>);</span><br><span class="line">                latch.countDown();</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">500</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            latch.await();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"线程安全自增值："</span>+safe.get(<span class="keyword">this</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在创建AtomicIntegerFieldUpdater时没有遵守使用规则，系统还是会抛一些异常，例如<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Exception in thread &quot;main&quot; java.lang.IllegalArgumentException: Must be integer type</span><br><span class="line">Exception in thread &quot;main&quot; java.lang.IllegalArgumentException: Must be volatile type</span><br></pre></td></tr></table></figure></p>
<p>结果：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">非线程安全自增值：4999</span><br><span class="line">线程安全自增值：5000</span><br></pre></td></tr></table></figure></p>
<h3 id="是否还有其他类型的包装类"><a href="#是否还有其他类型的包装类" class="headerlink" title="是否还有其他类型的包装类"></a>是否还有其他类型的包装类</h3><p>javaAPI除了提供了对int类型的原子操作封装的工具类，还提供了另外两项工具类：AtomicLongFieldUpdater、AtomicReferenceFieldUpdater。分别提供了对long以及对象引用类型的变量原子操作的封装。<br>这两个工具类的使用以及规则与上面提及的AtomicIntegerFieldUpdater一样。</p>
<h2 id="AtomicIntegerFieldUpdater实现"><a href="#AtomicIntegerFieldUpdater实现" class="headerlink" title="AtomicIntegerFieldUpdater实现"></a>AtomicIntegerFieldUpdater实现</h2><p>那么，Java是怎样实现对这些变量的分装？我们分别看下AtomicIntegerFieldUpdater和AtomicReferenceFieldUpdateer的源码。</p>
<h3 id="AtomicIntegerFieldUpdater源码实现"><a href="#AtomicIntegerFieldUpdater源码实现" class="headerlink" title="AtomicIntegerFieldUpdater源码实现"></a>AtomicIntegerFieldUpdater源码实现</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@CallerSensitive</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;U&gt; <span class="function">AtomicIntegerFieldUpdater&lt;U&gt; <span class="title">newUpdater</span><span class="params">(Class&lt;U&gt; tclass, String fieldName)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> AtomicIntegerFieldUpdaterImpl&lt;U&gt; (tclass, fieldName, Reflection.getCallerClass());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">AtomicIntegerFieldUpdaterImpl(<span class="keyword">final</span> Class&lt;T&gt; tclass, <span class="keyword">final</span> String fieldName, <span class="keyword">final</span> Class&lt;?&gt; caller) &#123;</span><br><span class="line">    <span class="keyword">final</span> Field field;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> modifiers;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        field = AccessController.doPrivileged(</span><br><span class="line">            <span class="keyword">new</span> PrivilegedExceptionAction&lt;Field&gt;() &#123;</span><br><span class="line">                <span class="function"><span class="keyword">public</span> Field <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> NoSuchFieldException </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> tclass.getDeclaredField(fieldName); <span class="comment">//通过反射获取变量的Field对象</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        modifiers = field.getModifiers();</span><br><span class="line">        sun.reflect.misc.ReflectUtil.ensureMemberAccess(caller, tclass, <span class="keyword">null</span>, modifiers);</span><br><span class="line">        ClassLoader cl = tclass.getClassLoader();</span><br><span class="line">        ClassLoader ccl = caller.getClassLoader();</span><br><span class="line">        <span class="keyword">if</span> ((ccl != <span class="keyword">null</span>) &amp;&amp; (ccl != cl) &amp;&amp;</span><br><span class="line">            ((cl == <span class="keyword">null</span>) || !isAncestor(cl, ccl))) &#123;</span><br><span class="line">            sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (PrivilegedActionException pae) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(pae.getException());</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (field.getType() != <span class="keyword">int</span>.class) <span class="comment">//判断变量类型是否为int</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Must be integer type"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!Modifier.isVolatile(modifiers)) <span class="comment">//判断变量是否为volatile</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Must be volatile type"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Access to protected field members is restricted to receivers only</span></span><br><span class="line">    <span class="comment">// of the accessing class, or one of its subclasses, and the</span></span><br><span class="line">    <span class="comment">// accessing class must in turn be a subclass (or package sibling)</span></span><br><span class="line">    <span class="comment">// of the protected member's defining class.</span></span><br><span class="line">    <span class="comment">// If the updater refers to a protected field of a declaring class</span></span><br><span class="line">    <span class="comment">// outside the current package, the receiver argument will be</span></span><br><span class="line">    <span class="comment">// narrowed to the type of the accessing class.</span></span><br><span class="line">    <span class="keyword">this</span>.cclass = (Modifier.isProtected(modifiers) &amp;&amp;</span><br><span class="line">                   tclass.isAssignableFrom(caller) &amp;&amp;</span><br><span class="line">                   !isSamePackage(tclass, caller))</span><br><span class="line">                  ? caller : tclass;</span><br><span class="line">    <span class="keyword">this</span>.tclass = tclass;</span><br><span class="line">    <span class="keyword">this</span>.offset = U.objectFieldOffset(field); <span class="comment">//获取对象内存的偏移量，用于从主内存拿值，保证参数对多个线程的可见性</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">addAndGet</span><span class="params">(T obj, <span class="keyword">int</span> delta)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> prev, next;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        prev = get(obj);</span><br><span class="line">        next = prev + delta;</span><br><span class="line">    &#125; <span class="keyword">while</span> (!compareAndSet(obj, prev, next));</span><br><span class="line">    <span class="keyword">return</span> next;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">get</span><span class="params">(T obj)</span> </span>&#123;</span><br><span class="line">    accessCheck(obj);</span><br><span class="line">    <span class="keyword">return</span> U.getIntVolatile(obj, offset);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>构造方法：<br>在AtomicIntegerFieldUpdater的构造方法中，使用大量的本地方法。主要完成以下功能：</li>
</ul>
<ol>
<li>通过反射获得了需要包装变量的Field对象</li>
<li>判断对象类型是否为int</li>
<li>判断变量对象是否为volatile</li>
</ol>
<ul>
<li>addAndGet方法<br>可以看到该方法主要有两个作用：</li>
</ul>
<ol>
<li>获取Field当前对象的值。从主内存获取值，保证可见性。U.getIntVolatile(obj, offset);</li>
<li>通过<a href="http://shuhao.gitee.io/blog/2018/01/25/CAS%E9%94%81%E6%9C%BA%E5%88%B6%EF%BC%8CAtomicInteger%E5%AE%9E%E7%8E%B0/" target="_blank" rel="external">CAS乐观锁</a>的方式，对变量进行原子操作。</li>
</ol>
<p>好了。AtomicIntegerFieldUpdater的实现原理已经解密了。主要通过反射，获取变零对象，然后通过volatile已经CAS乐观锁保证其：<strong>可见性</strong>，<strong>原子性</strong>从而实现变量的原子性转换。</p>
<h3 id="AtomicReferenceFieldUpdater"><a href="#AtomicReferenceFieldUpdater" class="headerlink" title="AtomicReferenceFieldUpdater"></a>AtomicReferenceFieldUpdater</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;U,W&gt; <span class="function">AtomicReferenceFieldUpdater&lt;U,W&gt; <span class="title">newUpdater</span><span class="params">(Class&lt;U&gt; tclass, Class&lt;W&gt; vclass, String fieldName)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> AtomicReferenceFieldUpdaterImpl&lt;U,W&gt;</span><br><span class="line">        (tclass, vclass, fieldName, Reflection.getCallerClass());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"> AtomicReferenceFieldUpdaterImpl(<span class="keyword">final</span> Class&lt;T&gt; tclass, <span class="keyword">final</span> Class&lt;V&gt; vclass, <span class="keyword">final</span> String fieldName, <span class="keyword">final</span> Class&lt;?&gt; caller) &#123;</span><br><span class="line">    <span class="keyword">final</span> Field field;</span><br><span class="line">    <span class="keyword">final</span> Class&lt;?&gt; fieldClass;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> modifiers;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        field = AccessController.doPrivileged(</span><br><span class="line">            <span class="keyword">new</span> PrivilegedExceptionAction&lt;Field&gt;() &#123;</span><br><span class="line">                <span class="function"><span class="keyword">public</span> Field <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> NoSuchFieldException </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> tclass.getDeclaredField(fieldName);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        modifiers = field.getModifiers();</span><br><span class="line">        sun.reflect.misc.ReflectUtil.ensureMemberAccess(</span><br><span class="line">            caller, tclass, <span class="keyword">null</span>, modifiers);</span><br><span class="line">        ClassLoader cl = tclass.getClassLoader();</span><br><span class="line">        ClassLoader ccl = caller.getClassLoader();</span><br><span class="line">        <span class="keyword">if</span> ((ccl != <span class="keyword">null</span>) &amp;&amp; (ccl != cl) &amp;&amp;</span><br><span class="line">            ((cl == <span class="keyword">null</span>) || !isAncestor(cl, ccl))) &#123;</span><br><span class="line">            sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);</span><br><span class="line">        &#125;</span><br><span class="line">        fieldClass = field.getType();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (PrivilegedActionException pae) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(pae.getException());</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (vclass != fieldClass)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ClassCastException();</span><br><span class="line">    <span class="keyword">if</span> (vclass.isPrimitive())</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Must be reference type"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!Modifier.isVolatile(modifiers))</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Must be volatile type"</span>);</span><br><span class="line">    <span class="keyword">this</span>.cclass = (Modifier.isProtected(modifiers) &amp;&amp;</span><br><span class="line">                   tclass.isAssignableFrom(caller) &amp;&amp;</span><br><span class="line">                   !isSamePackage(tclass, caller))</span><br><span class="line">                  ? caller : tclass;</span><br><span class="line">    <span class="keyword">this</span>.tclass = tclass;</span><br><span class="line">    <span class="keyword">this</span>.vclass = vclass;</span><br><span class="line">    <span class="keyword">this</span>.offset = U.objectFieldOffset(field);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> V <span class="title">getAndSet</span><span class="params">(T obj, V newValue)</span> </span>&#123;</span><br><span class="line">    accessCheck(obj);</span><br><span class="line">    valueCheck(newValue);</span><br><span class="line">    <span class="keyword">return</span> (V)U.getAndSetObject(obj, offset, newValue);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到AtomiceReferenceFieldUpdater的创建方法除了变量所在的类class对象外，还需要reference对应的类的class对象。另外其他的实现与AtomicIntegerFieldUpdter实现类似。</p>
<blockquote>
<blockquote>
<blockquote>
<p>参考<br><a href="http://www.blogjava.net/xylz/archive/2010/07/02/325079.html" target="_blank" rel="external">http://www.blogjava.net/xylz/archive/2010/07/02/325079.html</a><br><a href="https://blog.csdn.net/anLA_/article/details/78662383" target="_blank" rel="external">https://blog.csdn.net/anLA_/article/details/78662383</a></p>
</blockquote>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"># java</a>
          
            <a href="/blog/tags/concurrent/" rel="tag"># concurrent</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/06/14/Spring之PropertySourcesPlaceHolderConfigurer/" rel="next" title="Spring之PropertySourcesPlaceHolderConfigurer">
                <i class="fa fa-chevron-left"></i> Spring之PropertySourcesPlaceHolderConfigurer
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/06/21/mysql设置允许远程连接/" rel="prev" title="mysql设置允许远程连接">
                mysql设置允许远程连接 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">110</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">32</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">84</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#AtomicIntegerFieldUpdater是什么？"><span class="nav-number">1.</span> <span class="nav-text">AtomicIntegerFieldUpdater是什么？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#变量线程安全的三要素"><span class="nav-number">1.1.</span> <span class="nav-text">变量线程安全的三要素</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java保证变量的线程安全"><span class="nav-number">1.2.</span> <span class="nav-text">Java保证变量的线程安全</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#AtomicIntegerFieldupdateUpdater创建"><span class="nav-number">1.2.1.</span> <span class="nav-text">AtomicIntegerFieldupdateUpdater创建</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AtomicIntegerFieldUpdater使用"><span class="nav-number">1.3.</span> <span class="nav-text">AtomicIntegerFieldUpdater使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#是否还有其他类型的包装类"><span class="nav-number">1.4.</span> <span class="nav-text">是否还有其他类型的包装类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AtomicIntegerFieldUpdater实现"><span class="nav-number">2.</span> <span class="nav-text">AtomicIntegerFieldUpdater实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#AtomicIntegerFieldUpdater源码实现"><span class="nav-number">2.1.</span> <span class="nav-text">AtomicIntegerFieldUpdater源码实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AtomicReferenceFieldUpdater"><span class="nav-number">2.2.</span> <span class="nav-text">AtomicReferenceFieldUpdater</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
